<template>
  <div class="daidaBox">
    <el-row class="header">
      <el-col :span="5" class="callInfo-pie">
        <div class="showPie" ref="showPie"></div>
        <div class="showNum">
          {{bdqk.willCall}}/<span class="red">{{bdqk.hasCall}}</span>
        </div>
        <h3>计划完成概况</h3>
      </el-col>
      <el-col :span="17" :offset="2">
        <div class="callInfoGlo__tableBox">
           <div class="noWrapBox">
            <ul class="table ths">
              <li v-for="(title,index) in callInfoGlo.titles" :key="index">
                {{title}}
              </li>
            </ul>
            <ul class="table tds" v-for="(item,index) in callInfoGlo.tableData" :key="index">
              <li v-text="item.kfName"></li>
              <li v-text="item.hczl"></li>
              <li v-text="item.jtzl"></li>
              <li v-text="item.yyxzs"></li>
              <li v-text="item.wyxzs"></li>
              <li v-text="item.yxbmqzs"></li>
            </ul>
           </div>
        </div>
      </el-col>
    </el-row>
    <section class="callDetailWrapper">
      <el-row>
        <el-col :span="5" v-if="power !== 3 && power !== 4 ">
          
          <span style="width:29%;text-align:right;float:left;line-height:36px;">选择客服：</span>
          <el-select v-model="kfs.value" clearable placeholder="请选择客服" @change="handleCurrentChange(1)" style="width:55%;">
            <el-option v-for="item in kfs.options" :key="item.id" :label="item.UserName" :value="item.id">
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="5">
          <span style="width:29%;text-align:right;float:left;line-height:36px;">导入时间：</span>
          <el-select v-model="leadInTime.value" clearable placeholder="请选择导入时间" @change="handleCurrentChange(1)" style="width:55%;">
            <el-option v-for="item in leadInTime.options" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <span style="width:29%;text-align:right;float:left;line-height:36px;">拨打日期：</span>
          <el-date-picker v-model="callDateDur" type="daterange" placeholder="选择日期范围" @change="handleCurrentChange(1)" style="width:55%;">
          </el-date-picker>
        </el-col>
        <el-col :span="5">
          <span style="width:29%;text-align:right;float:left;line-height:36px;">拨打类型：</span>
          <el-select v-model="callType.value" clearable placeholder="请选择拨打类型" @change="handleCurrentChange(1)" style="width:55%;">
            <el-option v-for="item in callType.options" :key="item.id" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleCurrentChange(1)" style="width:25%">搜索</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <span style="width:29%;text-align:right;float:left;line-height:36px;">客服性质：</span>
          <el-select v-model="kfProps.value" clearable placeholder="请选择客服性质" @change="handleCurrentChange(1)" style="width:55%;">
            <el-option v-for="item in kfProps.options" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <span style="width:29%;text-align:right;float:left;line-height:36px;">拨打状态：</span>
          <el-select v-model="BodaState.value" clearable placeholder="请选择拨打状态" @change="handleCurrentChange(1)" style="width:55%;">
            <el-option v-for="item in bodaState.options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <span style="width:29%;text-align:right;float:left;line-height:36px;">接通状态：</span>
          <el-select v-model="jietongState.value" clearable placeholder="请选择接通状态" @change="handleCurrentChange(1)" style="width:55%;">
            <el-option v-for="item in jietongState.state" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <div class="kxz-daida__tableArea">
        <div class="tools">
          <div class='div1'>
            
              <el-button type="primary" @click="leadOutExcel" style="margin-bottom:20px;">
                导出excel
              </el-button>
            
          </div>
          <div class='div2' v-if='power===1'><!--控制只有夏寒梦可以导入-->
              <el-upload
                class="upload-demo dadai-upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                ref="uploadAvatar"
                accept="*"
                :multiple="false"
                :auto-upload="false">
                <el-button size="small" type="primary">导入excel</el-button>
            </el-upload>
            <el-button size="small" type="primary" @click="submitUpload">点击上传</el-button>
          </div>
        </div>
        <table class="daidalist">
          <tr>
            <th v-for="item in callInfoLoc.titles"
              :key="item.prop"
              v-text="item.label"
              :style="`width:${item.width};`"
            ></th>
          </tr>
          <tr v-for="(item,index) in callInfoLoc.tableData" :key="index">
            <td>{{item.bdqk}}</td>
            <td>{{item.xfpkf}}</td>
            <td>{{item.vip}}</td>
            <td>
              <router-link :to="`/vip-manage/detail/${item.fuid}/jbxx`" class="click">{{item.fuid}}</router-link>
            </td>
            <td>{{item.cName}}</td>
            <td>
              <img class="phoneIcon" src="./components/images/phone.png" @click="callPhone(item,item.fuid,id)">
              <span class="watch" @click="watch(index,item.fuid)" v-if="callInfoLoc.tableData.length > 0 && !watchPhone[index].isTrue">点击查看</span>
              <span v-if="watchPhone[index].isTrue" @click="callPhone(item)" style="cursor:pointer">{{item.cMtel}}</span>
            </td>
            <td>{{item.dsje}}</td>
            <td>{{item.sex}}</td>
            <td>{{item.khxz}}</td>
            <td>{{item.kfgroup}}</td>
            <td>{{item.jtqk}}</td>
            <td>
              <span class="red" v-text="item.yhyx"></span>/
              {{item.bz}}
            </td>
          </tr>
          <tr v-if="callInfoLoc.tableData.length === 0" >
            <td :colspan="callInfoLoc.titles.length">
              暂无数据
            </td>
          </tr>
        </table>
        <div class="pager" style="float:right;">
          <el-pagination @current-change="handleCurrentChange" 
          :page-size="callInfoLoc.pageSize" 
          layout="total,prev, pager, next, jumper" 
          :current-page="callInfoLoc.page" 
          :total="callInfoLoc.total">
          </el-pagination>
        </div>
      </div>
    </section>
    <el-dialog
      title="用户意向"
      :visible.sync="yxDialog.isOpen"
      :close-on-click-modal="false"
      :show-close="false"
      size="tiny"
      >
      <el-radio-group v-model="yxDialog.value">
        <el-radio v-for="item in yxDialog.options" :label="item.label" :key="item.label">{{item.text}}</el-radio>
      </el-radio-group>
      <el-input
        type="textarea"
        :rows="4"
        placeholder="请输入备注内容"
        v-model="yxDialog.remark" class="yx__textarea">
      </el-input>
      <p class="yx__submit">
        <el-button type="primary" @click="handleSubmitYXdialog">提交</el-button>
      </p>
    </el-dialog>
  </div>
</template>

<script>
import { dateFormat } from 'vux'
import {callout} from '../../config/mixin'

export default {
  name: 'daida',
  mixins: [callout],
  data() {
    const {power} = this.$store.getters.getUserInfo
    const kfsOptions = this.$store.getters.getKf
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      legend: {
        orient: 'vertical',
        x: 'right',
        data: ['拨打', '未拨打']
      },
      series: [
        {
          name: '拨打情况',
          type: 'pie',
          radius: ['50%', '70%'],
          label: {
            normal: {
              show: false,
            },
            emphasis: {
              show: false,
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          data: [
          ]
        }
      ]
    };

    const nowDate = new Date()
    return {
      id:this.$route.params.id,
      power,
      pie: {
        ins: null,
        baseOptions: option,
        data: [],
      },
      callInfoGlo: {
        titles: [
          '客服名字',
          '今日呼出总量',
          '今日接通总量',
          '有意向总数',
          '无意向总数',
          '意向不明确总数',
        ],
        tableData: []
      },
      //拨打情况
      bdqk:{
        willCall:0,
        hasCall:0,
      },
      // 导入时间
      leadInTime:{
        value:'',
        options:[]
      },
      // 拨打日期
      callDateDur: '',
      // 选择客服
      kfs: {
        value: '',
        options: kfsOptions
      },
      // 拨打类型
      callType: {
        value: '',
        options: [
          { value: 1, label: '通知（无业绩）' },
          { value: 2, label: '业绩目标' },
        ]
      },
      // 客服性质
      kfProps:{
        value:'',
        options:[]
      },
      //拨打状态
      bodaState:{
        value:'',
        options:[
          {value: 0,label:'未拨打'},
          {value: 1,label:'已拨打'},
        ]
      },
      //接通状态
      jietongState:{
        value:'',
        state:['已接通','未接通']
      },
      BodaState:{
        value:'',
        state:['已拨打','未拨打']
      },
      callInfoLoc: {
        page: 1,
        pageSize: 20,
        total: 0,
        titles: [
          {
            label: '拨打情况',
            prop: 'bdqk',
            width: '5%',
          },
          {
            label: '所属客服',
            prop: 'ykfname',
            width: '8%',
          },
          {
            label: 'vip等级',
            prop: 'vip',
            width: '8%',
          },
          {
            label: '用户id',
            prop: 'fuid',
            width: '10%',
          },
          {
            label: '姓名',
            prop: 'cName',
            width: '10%',
          },
          {
            label: '手机号',
            prop: 'cMtel',
            width: '15%',
          },
          {
            label: '目前待收',
            prop: 'dsje',
            // width: '10%',
          },
          {
            label: '性别',
            prop: 'sex',
            // width: '5%',
          },
          {
            label: '客户性质',
            prop: 'khxz',
            // width: '5%',
          },
          {
            label: '组名称',
            prop: 'kfgroup',
            // width: '10%',
          },
          {
            label: '接通情况',
            prop: 'jtqk',
            // width: '5%',
          },
          {
            label: '意见反馈/备注',
            prop: 'yhyx',
            // width: '10%',
          },
        ],
        tableData: []
      },
      watchPhone:[],
      yxDialog:{
        isOpen:false,
        // isOpen:true,
        id:null,      // 标记用户Id
        remark:'',
        value:'',
        options:[
          {label:1,text:'有意向'},
          {label:2,text:'无意向'},
          {label:3,text:'意向不明确'},
        ]
      }
    }
  },
  computed:{
    cuUserInfo(){
      return this.$store.getters.getUserInfo
    },
    cuCallType(){
      return this.$store.getters.callMsg.callType
    },
    cuDaida(){
      return this.$store.getters.daida
    },
    cuCallInfo(){
      return this.$store.getters.callInfo
    }
  },
  watch: {
    cuCallType(val){
      console.log('daida.callout:', val)
      if(val === 'callout'){
        this.yxDialog.isOpen = true
      }
    },
    'pie.data'(data) {
      const pieIns = this.pie.ins
      const baseOptions = this.pie.baseOptions
      //
      baseOptions.series[0].data = data
      pieIns.setOption(baseOptions)
    },
    cuDaida(val){
      const isOpen = this.yxDialog.isOpen
      console.log('daida:', val)
      if(!val && !isOpen){
        // 初始化watchPhone
        this.handleCurrentChange(this.callInfoLoc.page)
      }
    },
  },
  mounted() {
    const pieRef = this.$refs['showPie']
    
    this.pie.ins = this.$echarts.init(pieRef)
    
    // 非组长或主管指定客服id
    if(this.power === 3 || this.power === 4){
      this.kfs.value = this.cuUserInfo.id
    }

    // 获取导入时间
    this.getDrsj()
    // 获取客服性质
    this.getKfProps()

    this.handleCurrentChange(1)

    // 初始化watchPhone
    this.watchPhone = this.watchPhoneArr()

  },
  methods: {
    async submitUpload() {
        try{
          const formData = new FormData()
          const files = this.$refs.uploadAvatar.uploadFiles
          // 添加提交参数

          if(files.length > 0){
            formData.append('userfile', files[0]['raw'])
          }
          console.log(formData)
          const url = window.path + 'task/uploadLb.do?'
          const res = await fetch(url,{
            method:'post',
            mode:'cors',
            body:formData
          })
          const data = await res.json()
          if(data.state === 0 && data.content){
            this.$message({
              type:'success',
              message:'提交成功',
            })
            return
          }
          this.$message({
            type: 'error',
            message: '提交失败',
          })
        }catch(e){
          console.warn('接口kfgl/uploadQn.do:',e.message)
          this.$warn('接口kfgl/uploadQn.do执行出错')
        }
    },
    handleCurrentChange(page) {
      this.callInfoLoc.page = page
      // 每次要请求三个接口的数据
      // 获取计划概要
      this.getPieData()

      // 获取意向统计
      this.getXxtj()

      this.watchPhone = this.watchPhoneArr()
      // 获取待打列表
      this.getDaida()

    },
    handleSubmitYXdialog(){
      this.postYX()
    },
    // 导出excel
    leadOutExcel(){
      const callType  = this.callType.value || ''
      const xfpkfid = this.kfs.value || ''
      const khxz = this.kfProps.value || ''
      const leadInTime = this.leadInTime.value || ''
      const bodatxt = this.BodaState.value
      const jietong = this.jietongState.value || ''
      window.open(`${window.path}task/excel.do?type=` + callType
          +'&khxz=' + khxz
          +'&xfpkfid='+ xfpkfid
          +'&bdqk='+ bodatxt
          +'&jtqk='+ jietong
          +'&drsj=' + leadInTime
          +`&st=${this.callDateDur ? dateFormat(this.callDateDur[0],'YYYY-MM-DD') : ''}`
          +`&et=${this.callDateDur ? dateFormat(this.callDateDur[1],'YYYY-MM-DD') : ''}`)

    },
    // 查看手机
    watch (i,fuid) {
      // 如果用户id存在，则标记拨号
      if(fuid !== undefined){
        this.markDial(fuid)
      }
      this.watchPhone[i].isTrue = true
    },
    watchPhoneArr(){
      // 根据pageSize的值动态修改watchPhone的状态
      // 指定查询，翻页的时候进行watchPhone的更新
      const pageSize = this.callInfoLoc.pageSize
      const tmpa = []
      for(let i = 0; i < pageSize; i++){
        tmpa.push({
          isTrue:false
        })
      }
      return tmpa
    },
    // 客服性质
    async getKfProps(){
      const api = 'task/allKhxz.do'
      try{
        const {data} = await this.$get(this,{
          api,
        })
        if(data.state === 0){
          this.kfProps.options = data.content
          return
        }
        console.warn(`接口${api}失败信息:`,data.message)
      }catch(e){
        console.warn(`接口${api}执行出错信息:`, e.message)
        this.$warn(`接口${api}执行出错`)
      }
    },
    async callPhone(item,fuid){
      // 如果用户id存在，则标记拨号
      // if(fuid !== undefined){
      //   this.markDial(fuid)
      // }
      const {cMtel,id,type} = item
      try{
        // 判断是省内，还是省外
        const {data} = await this.$get(this,{
          api:'ajaxapi/isFouWz.do',
          data: {
            mobile: cMtel,
            yhm: this.cuUserInfo.usertel
          }
        })
        if (data.state === 0) {
          this.$confirm({
            message: '确认拨打？',
            success: ()=>{
              this.yxDialog.id = id
              this.$store.dispatch('updateDaida', {
                id,
                type,
              })
              this.callout(data.content)
            }
          })
        }
      }catch(e){
        console.warn('ajaxapi/isFouWz:', e.message)
        this.$warn('系统接口ajaxapi/isFouWz报错')
      }
    },
    // 标记拨打操作
    async  markDial(fuid){
      const api = 'member/looktel.do'
      try{
        const {data} = await this.$get(this,{
          api,
          data:{
            fuid
          }
        })
        if(data.state === 0){
          console.log(`接口${api}标记成功`)
          return
        }
        console.warn(`接口${api}标记失败信息:`,data.message)
      }catch(e){
        console.warn(`接口${api}执行出错信息:`, e.message)
        this.$warn(`接口${api}执行出错`)
      }
    },
    //
    async postYX(){
      const {value,remark,id,options} = this.yxDialog
      try{
        const {data} = await this.$post(this,{
          api:'task/updateyhyx.do',
          data:{
            yhyx:value,
            bz:remark,
            id
          }
        })
        if(data.state === 0){
          this.$message({
            message:'提交成功',
            type:'success'
          })
          //
          let selLabel
          switch(value){
            case 1:
              selLabel = '有意向'
              break
            case 2:
              selLabel = '无意向'
              break
            case 3:
              selLabel = '意向不明确'
              break
          }
          this.handleCurrentChange(this.callInfoLoc.page)
          // 初始化yxDialog信息
          this.yxDialog.value = ''
          this.yxDialog.remark = ''
          this.yxDialog.isOpen = false
        }
      }catch(e){
        console.warn('接口task/updateyhyx.do:',e.message)
        this.$warn('接口task/updateyhyx.do执行异常')
      }
    },
    // 计划总概
    async getPieData(){
      try{
        const {data} = await this.$get(this,{
          api:'task/jhwcgk.do',
          data:{
            type:this.callType.value,
            xfpkfid:this.kfs.value,
            drsj:this.leadInTime.value,
            jtqk:this.jietongState.value,
            bdqk:this.BodaState.value,
            khxz:this.kfProps.value,
            groupId:this.cuUserInfo.userGroupId
          }
        })
        if(data.state === 0){
          let pieData = []
          if(data.content){
            pieData = [
              {name:'拨打',value:data.content['已拨打']},
              {name:'未拨打',value:data.content['未拨打']},
            ]
          }else{
            pieData = [
              {name:'拨打',value:0},
              {name:'未拨打',value:0},
            ]
          }
          this.pie.data = pieData
          this.bdqk = {
            willCall:pieData[1].value,
            hasCall:pieData[0].value,
          }
          return
        }
       this.$warn('系统接口task/jhwcgk.do数据返回异常')
      }catch(e){
        console.log('task/jhwcgk.do:',e.message)
        this.$warn('系统接口task/jhwcgk.do执行出错')
      }
    },
    // 导入时间
    async getDrsj(){
      try{
        const {data} = await this.$get(this,{
          api:'task/loadDrsj.do',
        })
        if(data.state === 0){
          this.leadInTime.options = data.content
          return
        }
        this.$warn('系统接口task/loadDrsj.do数据返回异常')
      }catch(e){
        this.$warn('系统接口task/loadDrsj.do执行出错')
      }
    },
    // 意向统计
    async getXxtj(){
      console.log(this.power)
      let adminGroup = this.cuUserInfo.userGroupId
      if(this.power===1){
        adminGroup =''
      }
      try{
        const {data} = await this.$get(this,{
          api:'task/xxtj.do',
          data:{
            type:this.callType.value,
            groupid:adminGroup,
            xfpkfid:this.kfs.value,
            drsj:this.leadInTime.value,
            st:this.callDateDur && this.callDateDur[0] && dateFormat(this.callDateDur[0],'YYYY-MM-DD'),
            et:this.callDateDur && this.callDateDur[1] && dateFormat(this.callDateDur[1],'YYYY-MM-DD'),
            jtqk:this.jietongState.value,
            bdqk:this.BodaState.value,
            khxz:this.kfProps.value
          }
        })
        
        if(data.state === 0){
          this.callInfoGlo.tableData = data.content
          return
        }
        this.$warn('系统接口task/xxtj.do数据返回异常')
      }catch(e){
        console.warn('task/xxtj.do:',e.message)
        this.$warn('系统接口task/xxtj.do执行出错')
      }
    },
    // 待打列表
    async getDaida(){
      const {pageSize,page} = this.callInfoLoc

      try{
        const {data} = await this.$get(this,{
          api:'/task/loadplayTask.do',
          data:{
            type:this.callType.value,
            xfpkfid:this.kfs.value,
            khxz:this.kfProps.value,
            drsj:this.leadInTime.value,
            jtqk:this.jietongState.value,
            bdqk:this.BodaState.value,
            st:this.callDateDur && this.callDateDur[0] ? dateFormat(this.callDateDur[0],'YYYY-MM-DD') : '',
            et:this.callDateDur && this.callDateDur[1] ? dateFormat(this.callDateDur[1],'YYYY-MM-DD') : '',
            page,
            pageSize

          }
        })
        if(data.state === 0){
          if(page === 1){
            this.callInfoLoc.total = data.content.num
          }
          this.callInfoLoc.tableData = data.content.data


        }
      }catch(e){
        console.warn('接口task/loadplayTask.do:',e.message)
        this.$warn('接口task/loadplayTask.do执行出错')
      }
    },
  }
}

</script>

<style lang="scss" scoped>
$bdColor: #bfcbd9;
.daidaBox {
  background: #fff;
}

.callInfo-pie {
  position: relative;
  .showPie {
    width:100%;
    height:280px;
  }
  .showNum{
    position:absolute;
    top:40%;
    left:50%;
    transform:translateX(-50%);
    font-size:20px;
    .red{
      color:#FF4949;
    }
  }
  h3 {
    text-align: center;
    line-height: 35px;
    font-size: 18px;
  }
}
.phoneIcon{
    // transform:translateY(3px) scale(.9,.9);
    cursor:pointer;
  }
.header {
  padding: 20px;
}

.red{
  color:#FF4949;
}

.click{
  color:#20A0FF;
}

.callInfoGlo__tableBox {
  position:relative;
  width:100%;
  height:295px;
  overflow-x:auto;
  padding-top:20px;
  .noWrapBox{
    position:absolute;
    display:flex;
    flex-wrap:nowrap;
  }
  .table {
    float: left;
    text-align: center;
    border-top:1px solid $bdColor;
    &:last-child{
      border-right:1px solid $bdColor;
    }
    border-top:1px solid $bdColor;
    &.ths {
      width: 150px;
    }
    &.tds {
      width: 80px;
    }
    li {
      line-height: 36px;
      font-size: 14px;
      border-left: 1px solid $bdColor;
      border-bottom: 1px solid $bdColor;
    }
  }
}

.callDetailWrapper{
  border-top:1px solid $bdColor;
  padding-top:20px;
}
.el-row{
  padding-left:20px;
  margin-bottom:10px;
}
.dadai-upload{
  float:left;
}
.tools{
  padding:0 0 20px 20px;
}
.tools .div1{
  width:100px;
  float:left;
}
.tools .div2{
  width:800px;
  float:left;
}
.watch {
  color: #5394fc;
  cursor: pointer;
}

.daidalist{
  width:100%;
  margin-bottom:8px;
  text-align:center;
  border-left:1px solid $bdColor;
  border-top:1px solid $bdColor;
  font-size:14px;
  th,td{
    line-height:35px;
    border-right:1px solid $bdColor;
    border-bottom:1px solid $bdColor;
    
  }
}
.yx__textarea{
  margin-top:8px;
}
.yx__submit{
  padding-top:10px;
  text-align:center;
}
.el-upload,.el-upload-list{
  float:left;
}
.el-button--small{
  margin-left:50px;
}
</style>

